package cn.tedu.charging.order.config;

import cn.tedu.charging.order.mqtt.MqttConsumer;
import cn.tedu.charging.order.mqtt.MqttContext;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class MqttConfiguration {
    private String username="admin";
    private String password="public";
    private String host="tcp://localhost:1883";
    private String clientId="order_service_client";

    //mapper注入进去的context装配过来 new MqttConsumer的时候传进去 在MqttConsumer里也可以使用mapper
    @Autowired
    private MqttContext mqttContext;
    @Bean
    public MqttClient mqttClient() throws MqttException {

        //通过连接地址和客户端id进行连接
        //客户端id的目的是告诉我们的服务器,谁在链接它
        MqttClient mqttClient = new MqttClient(host, clientId);

        //连接相关的配置
        MqttConnectOptions conOpts = new MqttConnectOptions();
        //用户名
        conOpts.setUserName(username);
        //密码
        conOpts.setPassword(password.toCharArray());
        //自动重连
        conOpts.setAutomaticReconnect(true);
        //版本号设置
        conOpts.setMqttVersion(MqttConnectOptions.MQTT_VERSION_3_1_1);
        //清理会话session
        conOpts.setCleanSession(true);
        //
        mqttClient.setCallback(new MqttConsumer(mqttClient,mqttContext));

        //进行连接
        mqttClient.connect(conOpts);
        return mqttClient;
    }
}
